package com.dz.lm.web.controller.h5;

import com.alibaba.fastjson.JSONObject;
import com.dz.lm.common.dto.AgentProductDTO;
import com.dz.lm.common.dto.ProductDTO;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.util.FileUploadUtil;
import com.dz.lm.common.utils.json.JsonUtils;
import com.dz.lm.common.utils.security.TokenProccess;
import com.dz.lm.dao.userinvite.read.UserInviteDao;
import com.dz.lm.domain.user.SmsInfo;
import com.dz.lm.domain.userinvite.UserInvite;
import com.dz.lm.service.account.AccountService;
import com.dz.lm.service.agentreview.AgentReviewService;
import com.dz.lm.service.appLogin.AppLoginService;
import com.dz.lm.service.business.ApplyProductService;
import com.dz.lm.service.goldagent.GoldAgentService;
import com.dz.lm.service.log.LoginLogService;
import com.dz.lm.service.manager.ManagerService;
import com.dz.lm.service.product.AgentProductService;
import com.dz.lm.service.product.ProductService;
import com.dz.lm.service.userapply.UserApplyService;
import com.dz.lm.service.userproduct.UserProductService;
import com.dz.lm.web.controller.Basic2Control;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

/**
 * 登录
 * 
 * @author zhanghairong
 */
@Controller
@RequestMapping("/rewriteUrl/h5/weijie")
public class WeijieH5Control extends Basic2Control{
	
	public Logger logger = LogManager.getLogger(WeijieH5Control.class);

	@Resource(name = "readUserInviteDao")
	private UserInviteDao readUserInviteDao;
	@Autowired
    private AppLoginService appLoginService;
	
	@Autowired
    private LoginLogService loginLogService;
	
	@Autowired
    private AccountService accountService;
	
    @Autowired
    private ManagerService managerService;

    @Autowired
    private ApplyProductService applyProductService;
    
    @Autowired
    private ProductService productService;
    
    @Autowired
    private AgentProductService agentProductService;
    
    @Autowired
    private GoldAgentService goldAgentService;

    @Autowired
	private UserApplyService userApplyService;

    @Autowired
	private UserProductService userProductService;

    @Autowired
	private AgentReviewService agentReviewService;
    /**
     * app登录验证
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/validateLogin")
    public Map<String, Object> validationLogin(HttpServletRequest request) throws ServiceException {
    	System.out.println("App login is starting!");
    	@SuppressWarnings("unchecked")
    	Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
    	JSONObject subjo = null;
    	//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("mobilePhone");
		inparam.add("password");
//		inparam.add("pushToken");
		for (String in : inparam) {
			if (!param.containsKey(in)) {
				subjo = new JSONObject();
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return subjo;
			}
		}
		String mobilePhone = param.get("mobilePhone").toString();
		String password = param.get("password").toString();
		String pushToken = param.get("pushToken") != null? param.get("pushToken").toString() : "";
		Map<String, Object> qryParam = new HashMap<String, Object>();
		qryParam.put("mobilePhone", mobilePhone);
		qryParam.put("password", password);
		qryParam.put("pushToken", pushToken);
		Map<String, Object> user = appLoginService.qryUserInfo(qryParam);
		if (user == null || user.isEmpty() ) {
			subjo = new JSONObject();
	    	subjo.put("result", "03");
	    	subjo.put("message", "您的账户不存在，请确认账户是否正确！");
	    	return subjo;
		} else if (!password.equals(user.get("passWord"))) {
			subjo = new JSONObject();
	    	subjo.put("result", "02");
	    	subjo.put("message", "您的账户或密码不正确，请重新输入！");
	    	return subjo;
		} else {
			Object userId = user.get("userId");
			param.put("userId", userId);
			qryParam.put("userId", userId);
			//记录登录日志
			loginLogService.addLoginLog(param);
			String token = TokenProccess.getToken();
			param.put("token", token);
			Map<String, Object> tokenMap = appLoginService.qryRyToken(param);
			Object ryToken = "";
			if (tokenMap != null && !tokenMap.isEmpty()) {
				ryToken = tokenMap.get("ryToken");
			}
			Map<String, Object> retData = appLoginService.qryFavoriteMoneyBarList(param);
			subjo = new JSONObject();
			UserInvite userInvite = readUserInviteDao.selectByUserId(Integer.valueOf(userId.toString()));
			if(userInvite != null){
				subjo.put("subCode",userInvite.getCode() );
			}
			subjo.put("isOn", retData.get("isOn"));
			subjo.put("userInfo", user);
			subjo.put("accessToken", token);
			subjo.put("ryToken", ryToken);
			subjo.put("barList", retData.get("barList"));
			subjo.put("appVerInfo", retData.get("appVerInfo"));
	    	subjo.put("result", "00");
	    	subjo.put("message", "登录成功！");
	    	//保存token信息
	    	loginLogService.addAccessToken(param);
	    	//创建账户信息
	    	accountService.addAccount(param);
		}
		return subjo;
    }

    /**
     * app发送短信验证码
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/sendsms")
    public Map<String, Object> sendsms(HttpServletRequest request) throws ServiceException{
    	@SuppressWarnings("unchecked")
		Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
		JSONObject subjo = new JSONObject();
    	//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("mobilePhone");
		inparam.add("type");
		for (String in : inparam) {
			if (!param.containsKey(in)) {
				subjo = new JSONObject();
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return subjo;
			}
		}
		String mobilePhone = param.get("mobilePhone").toString();
		String type = param.get("type").toString();
		//校验该账户是否已注册
		Integer cnt = appLoginService.selectByMobilePhoneCnt(mobilePhone);
		if ("1".equals(type)) {
			if(cnt > 0) {
				subjo = new JSONObject();
		    	subjo.put("result", "02");
		    	subjo.put("message", "您已注册过该应用，若忘记密码请返回首页找回密码，否则可直接登录");
		    	return subjo;
			}
		} else {
			if(cnt <= 0) {
				subjo = new JSONObject();
		    	subjo.put("result", "03");
		    	subjo.put("message", "您还不是该应用成员，请确认输入的账号是否正确?");
		    	return subjo;
			}
		}
		String sendRes = appLoginService.sendSms(mobilePhone);
		subjo = new JSONObject();
		if ("0".equals(sendRes)) {
	    	subjo.put("result", "00");
	    	subjo.put("message", "发送成功，请注意查收");
		} else if("LM1001".equals(sendRes)){
	    	subjo.put("result", "01");
	    	subjo.put("message", "您的短信发送频率过高，请稍后再试");
		} else if("LM1002".equals(sendRes)){
	    	subjo.put("result", "01");
	    	subjo.put("message", "很抱歉，发送短信验证码次数超限，请您明日再试");
		} else {
	    	subjo.put("result", "01");
	    	subjo.put("message", "发送失败");
		}
    	return subjo;
    }
    
    /**
     * 小程序注册接口
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/signUp")
    public Map<String, Object> signUp(HttpServletRequest request) throws ServiceException {
    	@SuppressWarnings("unchecked")
		Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
    	if(param == null){
			String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
			 param = JsonUtils.readValue(reqData.toString());
		}
    	JSONObject subjo = new JSONObject();
		//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("mobilePhone");
		inparam.add("verifyCode");
		inparam.add("password");
		inparam.add("confirmPassword");
		for (String in:inparam) {
			if (!param.containsKey(in)) {
				subjo = new JSONObject();
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return subjo;
			}
		}
		String mobilePhone = param.get("mobilePhone").toString();
		String verifyCode = param.get("verifyCode").toString();
		String password = param.get("password").toString();
		String confirmPassword = param.get("confirmPassword").toString();
		//密码与确认密码进行比较
		if (password != null && !password.equals(confirmPassword)) {
			subjo = new JSONObject();
	    	subjo.put("result", "02");
	    	subjo.put("message", "密码与确认密码不一致，请重新输入！");
	    	return subjo;
		}
		//校验短信验证码
		boolean checkFlag = false;
		//查询数据库，查到该手机号码最新的未过期的且未被验证的短信验证码与参数短信验证码进行匹配
		SmsInfo si = appLoginService.qrySmsInfo(mobilePhone);
		if (si!= null){ 
			if (verifyCode.equals(si.getCode())) {
				checkFlag = true;
				//验证通过后更新该条记录的验证状态和验证时间
				appLoginService.updateSmsInfo(si);
			}
		}
		if (!checkFlag) {
			subjo = new JSONObject();
	    	subjo.put("result", "01");
	    	subjo.put("message", "短信验证码错误，请重新输入");
	    	return subjo;
		}
		//校验该账户是否已注册
		Integer cnt = appLoginService.selectByMobilePhoneCnt(mobilePhone);
		if(cnt > 0) {
			subjo = new JSONObject();
	    	subjo.put("result", "03");
	    	subjo.put("message", "您已是找钱吧成员啦~是否直接登录?");
	    	return subjo;
		}
		//保存注册数据
		if (param.get("pwdLevel") == null || "".equals(param.get("pwdLevel").toString())) {
			param.put("pwdLevel","02");
		}
		cnt = appLoginService.addNewUserInfo(param);
		//返回注册结果
		if (cnt > 0) {
			subjo = new JSONObject();
	    	subjo.put("result", "00");
	    	subjo.put("message", "注册成功");
	    	return subjo;
		} else {
			subjo = new JSONObject();
	    	subjo.put("result", "04");
	    	subjo.put("message", "数据保存异常，注册失败");
	    	return subjo;
		}
    }
    
    /**
     * app找回密码
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/findPassword")
    public Map<String, Object> findPassword(HttpServletRequest request) throws ServiceException {
    	@SuppressWarnings("unchecked")
    	Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
		JSONObject subjo = new JSONObject();
		//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("mobilePhone");
		inparam.add("verifyCode");
		inparam.add("password");
		inparam.add("confirmPassword");
		for (String in:inparam) {
			if (!param.containsKey(in)) {
				subjo = new JSONObject();
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return subjo;
			}
		}
		String mobilePhone = param.get("mobilePhone").toString();
		String verifyCode = param.get("verifyCode").toString();
		String password = param.get("password").toString();
		String confirmPassword = param.get("confirmPassword").toString();

		//密码与确认密码进行比较
		if (password != null && !password.equals(confirmPassword)) {
			subjo = new JSONObject();
	    	subjo.put("result", "02");
	    	subjo.put("message", "密码与确认密码不一致，请重新输入！");
	    	return subjo;
		}
		
		//校验该账户是否已注册
		Integer cnt = appLoginService.selectByMobilePhoneCnt(mobilePhone);
		if(cnt <= 0) {
			//未注册
			subjo = new JSONObject();
	    	subjo.put("result", "02");
	    	subjo.put("message", "您还不是找钱吧成员，请确认输入的账号是否正确?");
	    	return subjo;
		}
		
		//校验短信验证码
		boolean checkFlag = false;
		//查询数据库，查到该手机号码最新的未过期的且未被验证的短信验证码与参数短信验证码进行匹配
		SmsInfo si = appLoginService.qrySmsInfo(mobilePhone);
		if (si!= null){ 
			if (verifyCode.equals(si.getCode())) {
				checkFlag = true;
				//验证通过后更新该条记录的验证状态和验证时间
				appLoginService.updateSmsInfo(si);
			}
		}
		if (!checkFlag) {
			subjo = new JSONObject();
	    	subjo.put("result", "01");
	    	subjo.put("message", "短信验证码错误，请重新输入");
	    	return subjo;
		}

		//更新用户数据
		if (param.get("pwdLevel") == null || "".equals(param.get("pwdLevel").toString())) {
			param.put("pwdLevel","02");
		}
		cnt = appLoginService.updateUserInfo(param);
		//返回更新结果
		if (cnt > 0) {
			subjo = new JSONObject();
	    	subjo.put("result", "00");
	    	subjo.put("message", "找回密码成功");
	    	return subjo;
		} else {
			subjo = new JSONObject();
	    	subjo.put("result", "04");
	    	subjo.put("message", "数据保存异常，找回密码失败");
	    	return subjo;
		}
    }
    
    /**
     * 查询个人主页顶部信息
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/qryUserHomeInfo")
    public Map<String, Object> qryUserHomeInfo(HttpServletRequest request) throws ServiceException {
    	@SuppressWarnings("unchecked")
    	Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
    	JSONObject subjo = new JSONObject();
		if (param.get("userId") == null || "".equals(param.get("userId"))) {
			param.put("userId", request.getAttribute("userId"));
		}
		param.put("activeUserId", param.get("userId"));
		Map<String, Object> data = managerService.qryUserHomeInfo(param);
		if (data != null && !data.isEmpty()) {
			subjo.put("result", "00");
	    	subjo.put("message", "查询成功");
	    	subjo.putAll(data);
		} else {
			subjo.put("result", "01");
	    	subjo.put("message", "未查的数据");
		}
		return parameterPackage(request, subjo);
    }
    
    /**
     * 查询发布的信息列表（包括代理产品）
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/qryUserHomeProducts")
    public Map<String, Object> qryUserHomeProducts(HttpServletRequest request) throws ServiceException {
    	@SuppressWarnings("unchecked")
    	Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
		JSONObject subjo = null;
		//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("position");
		inparam.add("size");
		for (String in : inparam) {
			if (!param.containsKey(in)) {
				subjo = new JSONObject();
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterPackage(request, subjo);
			}
		}
	
		String position = param.get("position") != null? param.get("position").toString() : "0";
		String size = param.get("size") != null? param.get("size").toString() : "10";
		param.put("position", Integer.valueOf(position) * Integer.valueOf(size));
		param.put("size", Integer.valueOf(size));
		if (param.get("userId") == null || "".equals(param.get("userId"))) {
			param.put("userId", request.getAttribute("userId"));
		}
		param.put("activeUserId", param.get("userId"));
		Map<String, Object> retData = managerService.qryUserHomeProducts(param);
		subjo = new JSONObject();
		subjo.put("result", "00");
		subjo.put("message", "SUCCESS");
		subjo.put("productList", retData.get("productList"));
		int count = (int) retData.get("count");
		int page = 0;
		if (count % Integer.valueOf(size) > 0) {
			page = count / Integer.valueOf(size) + 1;
		} else {
			page = count / Integer.valueOf(size);
		}
		subjo.put("count", count);
		subjo.put("page", page);
		return parameterPackage(request, subjo);
    }
    
    /**
     * 查询历史评论列表
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/qryUserHomeComments")
    public Map<String, Object> qryUserHomeComments(HttpServletRequest request) throws ServiceException {
    	@SuppressWarnings("unchecked")
    	Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
    	JSONObject subjo = new JSONObject();
		//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("position");
		inparam.add("size");
		for (String in : inparam) {
			if (!param.containsKey(in)) {
				subjo = new JSONObject();
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterPackage(request, subjo);
			}
		}
		String position = param.get("position") != null? param.get("position").toString() : "0";
		String size = param.get("size") != null? param.get("size").toString() : "10";
		param.put("position", Integer.valueOf(position) * Integer.valueOf(size));
		param.put("size", Integer.valueOf(size));
		if (param.get("userId") == null || "".equals(param.get("userId"))) {
			param.put("userId", request.getAttribute("userId"));
		}
		Map<String, Object> retData = managerService.qryUserHomeComments(param);
		subjo = new JSONObject();
		subjo.put("result", "00");
		subjo.put("message", "查询成功");
		subjo.put("commentList", retData.get("commentList"));
		int count = (int) retData.get("count");
		int page = 0;
		if (count % Integer.valueOf(size) > 0) {
			page = count / Integer.valueOf(size) + 1;
		} else {
			page = count / Integer.valueOf(size);
		}
		subjo.put("count", count);
		subjo.put("page", page);
		return parameterPackage(request, subjo);
    }
    
    /**
     * 查询申请记录列表
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/qryMyAgentProductApplyList")
    public Map<String, Object> qryMyAgentProductApplyList(HttpServletRequest request) throws ServiceException {
    	@SuppressWarnings("unchecked")
    	Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
    	JSONObject subjo = null;
    	//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("position");
		inparam.add("size");
		for (String in : inparam) {
			if (!param.containsKey(in)) {
				subjo = new JSONObject();
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterPackage(request, subjo);
			}
		}
		String position = param.get("position") != null? param.get("position").toString() : "0";
		String size = param.get("size") != null? param.get("size").toString() : "10";		
		param.put("position", Integer.valueOf(position) * Integer.valueOf(size));
		param.put("size", Integer.valueOf(size));
		if (param.get("userId") == null || "".equals(param.get("userId"))) {
			param.put("userId", request.getAttribute("userId"));
		}
		Map<String, Object> retData = managerService.qryMyAgentProductApplyList(param);
		subjo = new JSONObject();
		subjo.put("result", "00");
    	subjo.put("message", "SUCCESS");
    	subjo.put("applyList", retData.get("applyList"));
		int count = (int) retData.get("count");
		int page = 0;
		if (count % Integer.valueOf(size) > 0) {
			page = count / Integer.valueOf(size) + 1;
		} else {
			page = count / Integer.valueOf(size);
		}
    	subjo.put("count", count);
    	subjo.put("page", page);
		return parameterPackage(request, subjo);
    }
    
    /**
     * 查询创建的产品详情
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/getProductDetail")
	public Map<String, Object> getProductDetail(HttpServletRequest request) throws ServiceException {
    	@SuppressWarnings("unchecked")
    	Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
		JSONObject subjo = new JSONObject();
		if (param.get("userId") == null || "".equals(param.get("userId"))) {
			param.put("userId", request.getAttribute("userId"));
		}
		ProductDTO productDTO = productService.selectByPrimaryKey(param);
		subjo.put("result", "00");
    	subjo.put("message", "SUCCESS");
		subjo.put("productInfo", productDTO);
		return parameterPackage(request, subjo);
	}
    
    /**
     * 查询代理的产品详情
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/getAgentProductDetail")
	public Map<String, Object> getAgentProductDetail(HttpServletRequest request) throws ServiceException {
    	@SuppressWarnings("unchecked")
    	Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
		JSONObject subjo = new JSONObject();
		if (param.get("userId") == null || "".equals(param.get("userId"))) {
			param.put("userId", request.getAttribute("userId"));
		}
		AgentProductDTO AgentProductDTO = agentProductService.selectByPrimaryKey(param);
		subjo.put("result", "00");
    	subjo.put("message", "SUCCESS");
		subjo.put("productInfo", AgentProductDTO);
		return parameterPackage(request, subjo);
    }
    
    /**
     * 申请产品
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/applyProduct")
    public Map<String, Object> applyProduct(HttpServletRequest request) throws ServiceException {
    	@SuppressWarnings("unchecked")
    	Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
		if (param.get("userId") == null || "".equals(param.get("userId"))) {
			param.put("userId", request.getAttribute("userId"));
		}
    	Map<String, Object> returnMap = applyProductService.insert(param);
		JSONObject subjo = new JSONObject();
		subjo.put("result", returnMap.get("result"));
		subjo.put("message", returnMap.get("message"));
		return parameterPackage(request, subjo);
    }
    
    /**
     * 添加借贷名片信息
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/addCreditCardInfo")
    public Map<String, Object> addCreditCardInfo(HttpServletRequest request) throws ServiceException {
    	Object imgUrl = request.getAttribute("imgUrl");
    	@SuppressWarnings("unchecked")
		Map<String, Object> images = (Map<String, Object>) request.getAttribute("images");
    	Map<String, Object> urlMap = new HashMap<String, Object>();
    	if (images != null && !images.isEmpty()) {
    		urlMap = FileUploadUtil.uploadByInStream(images, imgUrl, "creditCard");
    	}
    	@SuppressWarnings("unchecked")
		Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
    	JSONObject subjo = null;
		//用户编码
		if (param.get("userId") == null || "".equals(param.get("userId"))) {
			param.put("userId", request.getAttribute("userId"));
		}
		Set<String> keys = urlMap.keySet();
		for (String key : keys) {
			param.put(key, imgUrl + urlMap.get(key).toString());
		}
		//借贷名片是否已开通（0：未开通 1：已开通）
		String openCreditCardFlag = "1";
		param.put("openCreditCardFlag", openCreditCardFlag);
		int count = managerService.addCreditCardInfo(param);
		if (count > 0) {
			subjo = new JSONObject();
			subjo.put("result", "00");
	    	subjo.put("message", "添加成功");
	    	subjo.put("creditCardId", count);
		} else {
			subjo = new JSONObject();
	    	subjo.put("result", "01");
	    	subjo.put("message", "添加失败");
	    	subjo.put("creditCardId", "");
		}
		return parameterPackage(request, subjo);
    }

    /**
     * 修改借贷名片信息
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/updateCreditCardInfo")
    public Map<String, Object> updateCreditCardInfo(HttpServletRequest request) throws ServiceException {
    	Object imgUrl = request.getAttribute("imgUrl");
    	@SuppressWarnings("unchecked")
		Map<String, Object> images = (Map<String, Object>) request.getAttribute("images");
    	Map<String, Object> urlMap = new HashMap<String, Object>();
    	if (images != null && !images.isEmpty()) {
    		urlMap = FileUploadUtil.uploadByInStream(images, imgUrl, "creditCard");
    	}
    	@SuppressWarnings("unchecked")
		Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
    	JSONObject subjo = new JSONObject();
		//用户编码
		if (param.get("userId") == null || "".equals(param.get("userId"))) {
			param.put("userId", request.getAttribute("userId"));
		}
		Set<String> keys = urlMap.keySet();
		for (String key : keys) {
			param.put(key, imgUrl + urlMap.get(key).toString());
		}
		checkImage("image",param, 9);
		int count = managerService.updateCreditCardInfo(param);
		if (count == 1) {
			//物理删除用户操作删除的图片
			deleteImages(param.get("deleteFiles"));
			subjo.put("result", "00");
	    	subjo.put("message", "修改成功");
		} else {
	    	subjo.put("result", "01");
	    	subjo.put("message", "修改失败");
		}
		return parameterPackage(request, subjo);
    }
    
    /**
     * 图片上传
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/uploadCreditCardImage")
    public Map<String, Object> uploadCreditCardImage(HttpServletRequest request) throws ServiceException {
    	Object imgUrl = request.getAttribute("imgUrl");
    	@SuppressWarnings("unchecked")
		Map<String, Object> images = (Map<String, Object>) request.getAttribute("images");
    	Map<String, Object> urlMap = new HashMap<String, Object>();
    	JSONObject subjo = new JSONObject();
    	@SuppressWarnings("unchecked")
		Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
		String imgType = param.get("imgType").toString();
		String path = "";
		if ("1".equals(imgType)) {
			path = "needs";
		} else if ("2".equals(imgType)) {
			path = "product";
		} else if ("3".equals(imgType)) {
			path = "authManager";
		} else if ("4".equals(imgType)) {
			path = "moneyBar";
		} else if ("5".equals(imgType)) {
			path = "creditCard";
		}else if("6".equals(imgType)){
			path = "applyProduct"; //申请产品
		} else if("7".equals(imgType)){
			path = "product"; //添加产品
		}else if("8".equals(imgType)){
			path = "agentReivew"; //添加产品
		} else {
			subjo.put("result", "01");
	    	subjo.put("message", "上传失败");
	    	return parameterPackage(request, subjo);
		}
    	if (images != null && !images.isEmpty()) {
    		urlMap = FileUploadUtil.uploadByInStream(images, imgUrl, path);
    	}

		//用户编码
		if (param.get("userId") == null || "".equals(param.get("userId"))) {
			param.put("userId", request.getParameter("userId"));
		}
		Set<String> keys = urlMap.keySet();
		for (String key : keys) {
			param.put(key, imgUrl + urlMap.get(key).toString());
		}
		int count = 0;
		if ("1".equals(imgType)) {
			count = productService.modifyNeeds(param);
		} else if ("2".equals(imgType)) {
			count = productService.modifyProduct(param);
		} else if ("3".equals(imgType)) {
			Map<String, Object> retData = managerService.modifyManageAuthInfo(param);
			count = Integer.valueOf(retData.get("count").toString());
		} else if ("4".equals(imgType)) {
			//Nothing 暂无
		} else if ("5".equals(imgType)) {
			count = managerService.updateCreditCardInfo(param);
		}else if ("6".equals(imgType)) {
			count = userApplyService.updateImage(param);
		}else if("7".equals(imgType)){
			count = userProductService.updateImage(param);
		}else if ("8".equals(imgType)){
			count= agentReviewService.updateImage(param);
		}
		if (count == 1) {
			subjo.put("result", "00");
	    	subjo.put("message", "上传成功");
		} else {
	    	subjo.put("result", "01");
	    	subjo.put("message", "上传失败");
		}
		return parameterPackage(request, subjo);
    }
    
    /**
     * 查询借贷名片信息
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/qryCreditCardInfo")
    public Map<String, Object> qryCreditCardInfo(HttpServletRequest request) throws ServiceException {
    	@SuppressWarnings("unchecked")
		Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
    	JSONObject subjo = new JSONObject();
		//用户编码
		if (param.get("userId") == null || "".equals(param.get("userId"))) {
			param.put("userId", request.getAttribute("userId"));
		}
		Map<String, Object> creditCardInfo = managerService.qryCreditCardInfo(param);
		if (creditCardInfo != null) {
			subjo.put("result", "00");
	    	subjo.put("message", "查询成功");
	    	subjo.put("creditCardInfo", creditCardInfo);
		} else {
	    	subjo.put("result", "01");
	    	subjo.put("message", "查询失败");
	    	subjo.put("creditCardInfo", null);
		}
		return parameterPackage(request, subjo);
    }

    /**
     * 预览借贷名片信息
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/previewCreditCardInfo")
    public Map<String, Object> previewCreditCardInfo(HttpServletRequest request) throws ServiceException {
    	@SuppressWarnings("unchecked")
		Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
    	JSONObject subjo = new JSONObject();
		//用户编码
		if (param.get("userId") == null || "".equals(param.get("userId"))) {
			param.put("userId", request.getAttribute("userId"));
		}
		Map<String, Object> creditCardInfo = managerService.previewCreditCardInfo(param);
		if (creditCardInfo != null) {
			subjo.put("result", "00");
	    	subjo.put("message", "查询成功");
	    	subjo.put("creditCardInfo", creditCardInfo);
		} else {
	    	subjo.put("result", "01");
	    	subjo.put("message", "查询失败");
	    	subjo.put("creditCardInfo", null);
		}
		return parameterPackage(request, subjo);
    }

    /**
     * 查询个人主页申请记录列表
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/qryMyAllProductApplyList")
    public Map<String, Object> qryMyAllProductApplyList(HttpServletRequest request) throws ServiceException {
    	@SuppressWarnings("unchecked")
		Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
    	JSONObject subjo = null;
    	//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("position");
		inparam.add("size");
		for (String in : inparam) {
			if (!param.containsKey(in)) {
				subjo = new JSONObject();
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterPackage(request, subjo);
			}
		}
		String position = param.get("position") != null? param.get("position").toString() : "0";
		String size = param.get("size") != null? param.get("size").toString() : "10";		
		param.put("position", Integer.valueOf(position) * Integer.valueOf(size));
		param.put("size", Integer.valueOf(size));
		if (param.get("userId") == null || "".equals(param.get("userId"))) {
			param.put("userId", request.getAttribute("userId"));
		}
		Map<String, Object> retData = goldAgentService.qryMyAllProductApplyList(param);
		subjo = new JSONObject();
		subjo.put("result", "00");
    	subjo.put("message", "SUCCESS");
    	subjo.put("applyList", retData.get("applyList"));
    	subjo.put("historyApplyCount", retData.get("historyApplyCount"));
    	subjo.put("totalPayAmount", retData.get("totalPayAmount"));
		int count = (int) retData.get("count");
		int page = 0;
		if (count % Integer.valueOf(size) > 0) {
			page = count / Integer.valueOf(size) + 1;
		} else {
			page = count / Integer.valueOf(size);
		}
    	subjo.put("count", count);
    	subjo.put("page", page);
		return parameterPackage(request, subjo);
    }
    
    @ResponseBody
    @RequestMapping("/qry1LevelAgentProductList")
    public Map<String, Object> qry1LevelAgentProductList(HttpServletRequest request) throws ServiceException {
    	@SuppressWarnings("unchecked")
		Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
    	JSONObject subjo = new JSONObject();
		//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("position");
		inparam.add("size");
		for (String in : inparam) {
			if (!param.containsKey(in)) {
				subjo = new JSONObject();
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterPackage(request, subjo);
			}
		}
		String position = param.get("position") != null? param.get("position").toString() : "0";
		String size = param.get("size") != null? param.get("size").toString() : "10";
		param.put("position", Integer.valueOf(position) * Integer.valueOf(size));
		param.put("size", Integer.valueOf(size));
		if (param.get("userId") == null || "".equals(param.get("userId"))) {
			param.put("userId", request.getAttribute("userId"));
		}
		Map<String, Object> retData = managerService.qry1LevelAgentProductList(param);
		subjo = new JSONObject();
		subjo.put("result", "00");
		subjo.put("message", "查询成功");
		subjo.put("applyList", retData.get("_1LevelAgentProductList"));
		int count = (int) retData.get("count");
		int page = 0;
		if (count % Integer.valueOf(size) > 0) {
			page = count / Integer.valueOf(size) + 1;
		} else {
			page = count / Integer.valueOf(size);
		}
		subjo.put("count", count);
		subjo.put("page", page);
		return parameterPackage(request, subjo);
    }
    
    /**
     * 获取代理人列表
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/qryAgentList")
    public Map<String, Object> qryAgentList(HttpServletRequest request) throws ServiceException {
    	@SuppressWarnings("unchecked")
		Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
    	JSONObject subjo = new JSONObject();
    	//参数校验
		Vector<String> inparam = new Vector<String>();
		inparam.add("position");
		inparam.add("size");
		for (String in : inparam) {
			if (!param.containsKey(in)) {
		    	subjo.put("result", "01");
		    	subjo.put("message", "参数" + in + "异常");
		    	return parameterPackage(request, subjo);
			}
		}
		String position = param.get("position") != null? param.get("position").toString() : "0";
		String size = param.get("size") != null? param.get("size").toString() : "10";		
		param.put("position", Integer.valueOf(position) * Integer.valueOf(size));
		param.put("size", Integer.valueOf(size));
		Map<String, Object> retData = goldAgentService.qryAgentList(param);
		subjo.put("result", "00");
    	subjo.put("message", "SUCCESS");
    	subjo.put("agentList", retData.get("agentList"));
		int count = (int) retData.get("count");
		int page = 0;
		if (count % Integer.valueOf(size) > 0) {
			page = count / Integer.valueOf(size) + 1;
		} else {
			page = count / Integer.valueOf(size);
		}
    	subjo.put("count", count);
    	subjo.put("page", page);
		return parameterPackage(request, subjo);
    }

    /**
     * 查询钱吧列表
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/qryMoneyBarList")
    public Map<String, Object> qryMoneyBarList(HttpServletRequest request) throws ServiceException {
    	@SuppressWarnings("unchecked")
		Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
    	JSONObject subjo = new JSONObject();
		//用户编码
		if (param.get("token") != null && "8155bc545f84d9652f1012ef2bdfb6eb".equals(param.get("token"))) {
			List<Map<String, Object>> moneyBarList = managerService.qryMoneyBarList(param);
			if (moneyBarList != null) {
				subjo.put("result", "00");
		    	subjo.put("moneyBarList", moneyBarList);
			} else {
		    	subjo.put("result", "01");
		    	subjo.put("moneyBarList", null);
			}
		} else {
			subjo.put("result", "01");
	    	subjo.put("moneyBarList", null);
		}
		return subjo;
    }
    
    /**
     * 审核钱吧
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/auditMoneyBar")
    public Map<String, Object> auditMoneyBar(HttpServletRequest request) throws ServiceException {
    	@SuppressWarnings("unchecked")
		Map<String, Object> param  = request.getAttribute("reqData") != null ? (Map<String, Object>)request.getAttribute("reqData") : null;
    	JSONObject subjo = new JSONObject();
		//用户编码
    	if (param.get("token") != null && "8155bc545f84d9652f1012ef2bdfb6eb".equals(param.get("token"))) {
			int count = managerService.auditMoneyBar(param);
			if (count == 1) {
				subjo.put("result", "00");
		    	subjo.put("message", "审核成功");
			} else {
		    	subjo.put("result", "01");
		    	subjo.put("message", "审核失败");
			}
    	}
		return subjo;
    }
}
